package com.nuoniu.sibanyun.service.erp.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.entity.erp.ErpNumberSet;
import com.nuoniu.sibanyun.entity.erp.ErpPeriod;
import com.nuoniu.sibanyun.entity.erp.ErpProject;
import com.nuoniu.sibanyun.entity.erp.ErpProjectPlan;
import com.nuoniu.sibanyun.mapper.erp.ErpProjectMapper;
import com.nuoniu.sibanyun.service.erp.*;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  项目服务实现类
 * </p>
 *
 * @author baiqiang
 * @since 2020-10-12
 */
@Service
public class ErpProjectServiceImpl extends ServiceImpl<ErpProjectMapper, ErpProject> implements IErpProjectService {

    @Autowired
    private IErpAccountService erpAccountService;
    @Autowired
    private IErpNumberSetService numberSetService;
    @Autowired
    private IErpProjectPlanService projectPlanService;

    @Override
    public Page<ErpProject> pageList(Page pages, ErpProject project) {
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper<ErpProject> queryWrapper = new QueryWrapper<>(project);
        queryWrapper.eq("company_id", userInfo.getCompanyId());
        if(StringUtils.isNotBlank(project.getSearchKey())) {
            queryWrapper.and(wrapper -> wrapper.likeRight("code", project.getSearchKey()).or().like("name", project.getSearchKey()));
        }

        queryWrapper.orderByDesc("create_date");
        Page page = page(pages, queryWrapper);
        return page;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveErpProject(ErpProject project) {
        Integer currentAccountId = erpAccountService.getCurrentAccountId();
        //校验 数据
        checkErpProject(project);
        UserInfo userInfo = UserThreadLocal.get();
        project.setCompanyId(userInfo.getCompanyId());

        if(project.getId() != null) {
            project.setUpdateDate(LocalDateTime.now());
            project.setUpdateUserId(userInfo.getUserId());
            project.setUpdateUserName(userInfo.getRealName());
        }else {
            project.setCode(getCode());
            project.setCompanyId(userInfo.getCompanyId());
            project.setCreateUserId(userInfo.getUserId());
            project.setCreateDate(LocalDateTime.now());
            project.setAccountId(currentAccountId);
            project.setCreateUserName(userInfo.getRealName());
        }

        saveOrUpdate(project);
    }

    @Override
    public void checkErpProject(ErpProject project) {
        Integer currentAccountId = erpAccountService.getCurrentAccountId();
        UserInfo userInfo = UserThreadLocal.get();
        boolean haveName = baseMapper.isHaveName(userInfo.getCompanyId(), currentAccountId, project.getName(), project.getId());
        if (haveName) {
            throw new NuoNiuException("项目名称重复");
        }
        boolean haveCode = baseMapper.isHaveCode(userInfo.getCompanyId(), currentAccountId, project.getCode(), project.getId());
        if (haveCode) {
            throw new NuoNiuException("项目编码重复");
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deleteByIds(List<Long> ids) {
        for(Long id : ids) {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("project_id", id);
            List<ErpProjectPlan> projectPlans = projectPlanService.list(wrapper);
            if(projectPlans.size() > 0) {
                throw new NuoNiuException("请先删除项目计划,里程碑");
            }
        }
        removeByIds(ids);
    }

    @Override
    public String getCode() {
        UserInfo userInfo = UserThreadLocal.get();
        ErpNumberSet numberSet = numberSetService.getByCode("Project", userInfo.getCompanyId(), erpAccountService.getCurrentAccountId());
        String dateStr = numberSet.getMedian() == 1 ? "%Y-%m-%d" : "%Y-%m";
        String code = baseMapper.getCode(userInfo.getCompanyId(), dateStr);
        return numberSetService.getCode(numberSet, code);
    }

    @Override
    public ErpProject getByName(String projectName) {
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("company_id", userInfo.getCompanyId());
        wrapper.eq("name", projectName);
        wrapper.last("LIMIT 1");
        return this.getOne(wrapper);
    }

}
